package com.chao.demo.service.impl;

import com.chao.demo.bean.User;
import com.chao.demo.bean.RegisterRequest;
import com.chao.demo.common.ResponseResult;
import com.chao.demo.server.TestServer;
import com.chao.demo.service.AuthService;
import com.chao.demo.utils.PasswordUtil;
import com.chao.demo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户认证服务实现类
 */
@Service
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Autowired
    private TestServer testServer;
    
    @Autowired
    private PasswordUtil passwordUtil;
    
    @Override
    public ResponseResult<?> register(RegisterRequest request) {
        // 参数验证
        if (request.getAccount() == null || request.getAccount().trim().isEmpty()) {
            return ResponseResult.error("账号不能为空");
        }
        
        if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
            return ResponseResult.error("密码不能为空");
        }
        
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            return ResponseResult.error("两次输入的密码不一致");
        }
        
        if (request.getPhone() == null || request.getPhone().trim().isEmpty()) {
            return ResponseResult.error("手机号不能为空");
        }
        
        // 验证账号是否已存在
        if (testServer.getUserByAccount(request.getAccount()) != null) {
            return ResponseResult.error("账号已存在");
        }
        
        // 验证手机号是否已存在
        if (testServer.getUserByPhone(request.getPhone()) != null) {
            return ResponseResult.error("手机号已被注册");
        }
        
        // 创建用户
        User user = new User();
        user.setAccount(request.getAccount());
        // 加密密码
        user.setPassword(passwordUtil.encryptPassword(request.getPassword()));
        user.setPhone(request.getPhone());
        user.setStatus("1"); // 1表示正常状态
        
        // 保存用户
        boolean success = testServer.addUser(user);
        if (success) {
            return ResponseResult.success("注册成功");
        } else {
            return ResponseResult.error(500, "注册失败，请稍后重试");
        }
    }
    
    @Override
    public ResponseResult<String> login(String accountOrPhone, String password) {
        // 从数据库验证用户
        User dbUser = null;
        
        // 尝试使用账号登录
        dbUser = testServer.getUserByAccount(accountOrPhone);
        
        // 如果账号登录失败，尝试使用手机号登录
        if (dbUser == null) {
            dbUser = testServer.getUserByPhone(accountOrPhone);
        }
        
        // 验证密码
        if (dbUser != null && passwordUtil.verifyPassword(password, dbUser.getPassword())) {
            // 生成token
            String token = UUID.randomUUID().toString();
            // 存储用户信息到Redis，设置过期时间为1小时
            redisUtil.setEx(token, dbUser.getUsername() != null ? dbUser.getUsername() : dbUser.getAccount(), 
                1, TimeUnit.HOURS);
            
            return ResponseResult.success("登录成功", token);
        } else {
            return ResponseResult.error(401, "用户名或密码错误");
        }
    }
    
    @Override
    public ResponseResult<?> logout(String token) {
        if (token != null && redisUtil.hasKey(token)) {
            redisUtil.delete(token);
            return ResponseResult.success("退出成功");
        }
        return ResponseResult.error("无效的token");
    }
    
    @Override
    public ResponseResult<User> getUserInfo(String token) {
        if (token != null && redisUtil.hasKey(token)) {
            String username = redisUtil.get(token);
            
            // 返回用户信息
            User user = new User();
            user.setUsername(username);
            
            return ResponseResult.success("获取成功", user);
        }
        return ResponseResult.error(401, "未授权");
    }
}